<template>
  <div class="receipt-create-container">
    <div class="page-header">
      <h2 class="page-title">创建收货单</h2>
      <div class="page-actions">
        <el-button @click="goBack">
          <el-icon>
            <ArrowLeft/>
          </el-icon>
          返回
        </el-button>
      </div>
    </div>

    <el-card class="create-form-card">
      <el-alert
          v-if="formError"
          :title="formError"
          class="mb-20"
          show-icon
          type="error"
          @close="formError = ''"
      />

      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-position="right"
          label-width="90px"
      >
        <!-- 基本信息区域 -->
        <h3 class="form-section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货单号" prop="receiptNumber">
              <el-input
                  v-model="formData.receiptNumber"
                  disabled
                  placeholder="系统自动生成"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联订单" prop="orderId">
              <el-select
                  v-model="formData.orderId"
                  :loading="orderLoading"
                  :remote-method="searchOrders"
                  filterable
                  placeholder="请选择关联订单"
                  remote
                  style="width: 100%"
                  @change="handleOrderChange"
              >
                <el-option
                    v-for="item in orderOptions"
                    :key="item.id"
                    :label="item.orderNumber"
                    :value="item.id"
                >
                  <div class="order-option">
                    <div>单号: {{ item.orderNumber }}</div>
                    <div>供应商: {{ item.supplierName }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input
                  v-model="formData.supplierName"
                  disabled
                  placeholder="选择订单后自动填充"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货日期" prop="receiptDate">
              <el-date-picker
                  v-model="formData.receiptDate"
                  format="YYYY-MM-DD"
                  placeholder="选择收货日期"
                  style="width: 100%"
                  type="date"
                  value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货人" prop="consignee">
              <el-input
                  v-model="formData.consignee"
                  placeholder="请输入收货人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="待验收" value="待验收"></el-option>
                <el-option label="已验收" value="已验收"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input-number v-model="formData.totalAmount" :disabled="true" :precision="2"
                           style="width: 220px"></el-input-number>
          <span class="text-gray-500 ml-2">元 (根据商品明细自动计算)</span>
        </el-form-item>

<!--        <el-row :gutter="20">-->
<!--          &lt;!&ndash;          <el-col :span="12">&ndash;&gt;-->
<!--          &lt;!&ndash;            <el-form-item label="备注" prop="remark">&ndash;&gt;-->
<!--          &lt;!&ndash;              <el-input&ndash;&gt;-->
<!--          &lt;!&ndash;                  v-model="formData.remark"&ndash;&gt;-->
<!--          &lt;!&ndash;                  :rows="2"&ndash;&gt;-->
<!--          &lt;!&ndash;                  placeholder="请输入备注信息"&ndash;&gt;-->
<!--          &lt;!&ndash;                  type="textarea"&ndash;&gt;-->
<!--          &lt;!&ndash;              ></el-input>&ndash;&gt;-->
<!--          &lt;!&ndash;            </el-form-item>&ndash;&gt;-->
<!--          &lt;!&ndash;          </el-col>&ndash;&gt;-->
<!--        </el-row>-->

        <!-- 收货单明细 -->
        <div class="form-section">
          <h3 class="form-section-title">收货明细</h3>
          <div class="table-actions">
            <el-button type="primary" @click="addItem">
              <el-icon>
                <Plus/>
              </el-icon>
              添加物品
            </el-button>
          </div>

          <el-table :data="formData.items" border style="width: 100%">
            <el-table-column label="序号" type="index" width="50"></el-table-column>
            <el-table-column label="物品名称" min-width="200">
              <template #default="scope">
                <el-form-item
                    :prop="'items.' + scope.$index + '.itemName'"
                    :rules="{ required: true, message: '物品名称不能为空', trigger: 'blur' }"
                >
                  <el-input v-model="scope.row.itemName" placeholder="请输入物品名称"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="规格" min-width="150">
              <template #default="scope">
                <el-form-item :prop="'items.' + scope.$index + '.specification'">
                  <el-input v-model="scope.row.specification" placeholder="请输入规格"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单位" width="120">
              <template #default="scope">
                <el-form-item
                    :prop="'items.' + scope.$index + '.unit'"
                    :rules="{ required: true, message: '单位不能为空', trigger: 'blur' }"
                >
                  <el-input v-model="scope.row.unit" placeholder="单位"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="120">
              <template #default="scope">
                <el-form-item
                    :prop="'items.' + scope.$index + '.quantity'"
                    :rules="[
                      { required: true, message: '数量不能为空', trigger: 'blur' },
                      { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
                    ]"
                >
                  <el-input-number
                      v-model="scope.row.quantity"
                      :min="1"
                      controls-position="right"
                      style="width: 100%"
                      @change="calculateItemTotal(scope.$index)"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="150">
              <template #default="scope">
                <el-form-item
                    :prop="'items.' + scope.$index + '.unitPrice'"
                    :rules="[
                      { required: true, message: '单价不能为空', trigger: 'blur' },
                      { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
                    ]"
                >
                  <el-input-number
                      v-model="scope.row.unitPrice"
                      :min="0.01"
                      :precision="2"
                      controls-position="right"
                      style="width: 100%"
                      @change="calculateItemTotal(scope.$index)"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="金额" width="150">
              <template #default="scope">
                <el-form-item :prop="'items.' + scope.$index + '.total'">
                  <el-input v-model="scope.row.total" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeItem(scope.$index)">
                  <el-icon>
                    <Delete/>
                  </el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="total-amount">
            <span>总金额: </span>
            <span class="amount">{{ formatCurrency(calculateTotalAmount()) }}</span>
          </div>
        </div>

        <div class="form-actions">
          <el-button :loading="submitLoading" type="primary" @click="submitForm">
            <el-icon>
              <Check/>
            </el-icon>
            保存
          </el-button>
          <el-button @click="resetForm">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus';
import {ArrowLeft, Check, Delete, Plus, Refresh} from '@element-plus/icons-vue';
import type {Receipt, ReceiptItem} from '@/api/receipt';
import {createReceipt} from '@/api/receipt';
import {getOrderList} from '@/api/order';
import {removeToken} from '@/utils/storage';

const router = useRouter();
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const formError = ref('');
const orderLoading = ref(false);
const orderOptions = ref<any[]>([]);

// 表单数据
const formData = reactive({
  receiptNumber: '', // 系统生成
  orderId: null, // 使用null作为初始值，而不是空字符串
  orderNumber: '',
  supplierName: '',
  receiptDate: new Date().toISOString().slice(0, 10), // 格式化为YYYY-MM-DD字符串
  consignee: '',
  status: '待验收',
  remark: '',
  totalAmount: 0,
  items: [] as ReceiptItem[]
});

// 表单验证规则
const rules = {
  orderId: [
    {required: true, message: '请选择关联订单', trigger: 'change'},
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请选择关联订单'));
        } else {
          const orderId = typeof value === 'number' ? value : parseInt(String(value), 10);
          if (isNaN(orderId)) {
            callback(new Error('无效的订单ID格式'));
          } else {
            // 验证订单ID在可用列表中存在
            const exists = orderOptions.value.some(order =>
                Number(order.id) === orderId || String(order.id) === String(orderId)
            );

            if (!exists && orderOptions.value.length > 0) {
              callback(new Error('选择的订单不存在或已失效'));
            } else {
              callback();
            }
          }
        }
      },
      trigger: 'change'
    }
  ],
  receiptDate: [
    {required: true, message: '请选择收货日期', trigger: 'change'}
  ],
  consignee: [
    {required: true, message: '请输入收货人', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ]
};

// 初始化页面
onMounted(() => {
  // 清除可能存在的错误信息
  formError.value = '';

  // 初始添加一行空明细
  if (formData.items.length === 0) {
    addItem();
  }

  // 加载订单列表以供选择
  loadInitialOrders();
});

// 加载初始订单列表
const loadInitialOrders = async () => {
  orderLoading.value = true;
  try {
    const params = {
      pageNum: 1,
      pageSize: 20,
      status: '待收货' // 按需过滤状态
    };

    const res = await getOrderList(params);

    if (res.code === 200 && res.data) {
      if (res.data.records && Array.isArray(res.data.records)) {
        orderOptions.value = res.data.records;
      } else if (Array.isArray(res.data)) {
        orderOptions.value = res.data;
      }
    }
  } catch (error) {
    console.error('加载订单列表失败', error);
  } finally {
    orderLoading.value = false;
  }
};

// 搜索订单
const searchOrders = async (query: string) => {
  if (query.length < 2) return;

  orderLoading.value = true;
  try {
    const params = {
      orderNumber: query,
      pageNum: 1,
      pageSize: 10
    };
    const res = await getOrderList(params);
    if (res.code === 200 && res.data) {
      if (res.data.records && Array.isArray(res.data.records)) {
        orderOptions.value = res.data.records;
      } else if (Array.isArray(res.data)) {
        orderOptions.value = res.data;
      }
    }
  } catch (error) {
    console.error('搜索订单失败', error);
  } finally {
    orderLoading.value = false;
  }
};

// 处理订单选择变更
const handleOrderChange = async (orderId: string | number) => {
  if (!orderId) {
    // 清空相关字段
    formData.supplierName = '';
    formData.orderNumber = '';
    return;
  }

  // 清除之前的错误
  formError.value = '';

  // 在查找订单时统一使用string比较，因为select返回的可能是string类型
  const selectedOrder = orderOptions.value.find(item => String(item.id) === String(orderId));
  if (selectedOrder) {
    formData.supplierName = selectedOrder.supplierName;
    formData.orderNumber = selectedOrder.orderNumber;

    // 如果有订单明细，可以填充到收货单明细
    if (selectedOrder.items && Array.isArray(selectedOrder.items)) {
      // 询问是否填充订单明细
      ElMessageBox.confirm('是否使用订单明细填充收货单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 清空现有明细
        formData.items = [];
        // 填充订单明细
        selectedOrder.items.forEach((item: any) => {
          formData.items.push({
            itemName: item.itemName || item.productName,
            specification: item.specification,
            unit: item.unit,
            quantity: Number(item.quantity),
            unitPrice: Number(item.unitPrice || item.price),
            total: Number((Number(item.quantity) * Number(item.unitPrice || item.price)).toFixed(2))
          });
        });
        // 计算总金额
        calculateTotalAmount();
      }).catch(() => {
        // 用户取消，不进行操作
      });
    }
  } else {
    console.error('找不到对应ID的订单:', orderId);
    ElMessage.warning('无法获取订单详情，请重新选择订单');
    formData.supplierName = '';
    formData.orderNumber = '';
  }
};

// 添加明细项
const addItem = () => {
  formData.items.push({
    itemName: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0,
    total: 0
  });
};

// 移除明细项
const removeItem = (index: number) => {
  formData.items.splice(index, 1);
  calculateTotalAmount();
};

// 计算单项总额
const calculateItemTotal = (index: number) => {
  const item = formData.items[index];
  item.total = Number((item.quantity * item.unitPrice).toFixed(2));
  calculateTotalAmount();
};

// 计算总金额
const calculateTotalAmount = () => {
  const total = formData.items.reduce((sum, item) => {
    return sum + Number(item.total || 0);
  }, 0);
  formData.totalAmount = total;
  return total;
};

// 格式化货币
const formatCurrency = (value: number) => {
  return `¥ ${value.toFixed(2)}`;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 先清除之前的错误信息
  formError.value = '';

  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error('表单校验失败', fields);
      formError.value = '请完善表单信息';
      return;
    }

    if (formData.items.length === 0) {
      formError.value = '请至少添加一项收货明细';
      return;
    }

    // 验证订单ID是否有效
    if (!formData.orderId) {
      formError.value = '请选择关联订单';
      return;
    }

    submitLoading.value = true;

    try {
      // 确保orderId是数字类型
      const orderId = typeof formData.orderId === 'number'
          ? formData.orderId
          : parseInt(String(formData.orderId), 10);

      if (isNaN(orderId)) {
        formError.value = '无效的订单ID，请重新选择订单';
        return;
      }

      // 验证是否能在订单列表中找到该订单
      const orderExists = orderOptions.value.some(order =>
          Number(order.id) === orderId || String(order.id) === String(orderId)
      );

      if (!orderExists) {
        console.error(`订单ID ${orderId} 在可用订单列表中不存在`);
        formError.value = '选择的订单不存在或已失效，请重新选择';
        submitLoading.value = false;
        return;
      }

      // 准备提交数据
      const submitData: Receipt = {
        receiptNumber: '', // 使用空字符串，让后端自动生成
        orderId: String(orderId), // 确保是字符串类型
        totalAmount: formData.totalAmount,
        supplierName: formData.supplierName,
        status: formData.status,
        receiptDate: formData.receiptDate,
        orderNumber: formData.orderNumber,
        consignee: formData.consignee,
        items: formData.items.map(item => ({
          ...item,
          quantity: Number(item.quantity),
          unitPrice: Number(item.unitPrice),
          total: Number(item.total)
        }))
      };

      // // 添加额外字段
      // (submitData as any).orderNumber = formData.orderNumber;
      // (submitData as any).receiptDate = formData.receiptDate;
      // (submitData as any).consignee = formData.consignee;
      // (submitData as any).remark = formData.remark;

      const res = await createReceipt(submitData);

      if (res.code === 200) {
        ElMessage.success('创建收货单成功');
        router.push('/dashboard/receipt-list');
      } else {
        console.error('创建收货单失败，响应码:', res.code, '错误消息:', res.message);
        ElMessage.error(res.message || '创建失败');
        if (res.message && res.message.includes('无效')) {
          formError.value = '此订单无效，请选择其他订单';
        } else {
          formError.value = res.message || '创建收货单失败，请稍后再试';
        }
      }
    } catch (error: any) {
      console.error('创建收货单失败', error);

      // 处理401未授权错误
      if (error.code === 401) {
        ElMessage.error('登录已过期，请重新登录');
        removeToken();
        router.push('/login');
        return;
      }

      // 处理403错误
      if (error.code === 403) {
        ElMessage.error('没有权限执行此操作，请联系管理员');
        return;
      }

      // 处理其他错误
      formError.value = error.message || '创建收货单失败，请稍后再试';

      if (error.message && error.message.includes('订单')) {
        formError.value = '此订单无效，请选择其他订单';
      }
    } finally {
      submitLoading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (!formRef.value) return;
  ElMessageBox.confirm('确定重置表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value!.resetFields();
    formData.items = [{
      itemName: '',
      specification: '',
      unit: '个',
      quantity: 1,
      unitPrice: 0,
      total: 0
    }];
    formData.totalAmount = 0;
    formError.value = '';
  });
};

// 返回上一页
const goBack = () => {
  router.back();
};
</script>

<style scoped>
.receipt-create-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.create-form-card {
  margin-bottom: 20px;
}

.form-section-title {
  font-size: 16px;
  font-weight: 600;
  margin: 20px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.total-amount {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
  font-size: 18px;
  margin-left: 10px;
}

.mb-20 {
  margin-bottom: 20px;
}

.order-option {
  display: flex;
  flex-direction: column;
}

.order-option div:first-child {
  font-weight: bold;
}

.order-option div:last-child {
  font-size: 12px;
  color: #999;
}

/* 表格内输入框样式优化 */
:deep(.el-table .cell) {
  padding: 3px !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-input__wrapper),
:deep(.el-input-number .el-input__wrapper) {
  padding: 0 8px !important;
  box-shadow: 0 0 0 1px #dcdfe6 inset !important;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-right: 25px !important;
}

:deep(.el-table--border .el-table__cell) {
  padding: 2px !important;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

:deep(.el-table .el-form-item) {
  margin-bottom: 0 !important;
}

:deep(.el-table .el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 0;
}
</style>